﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using KeaoBase;
using System.Threading;
using System.IO;
using System.Xml;
using System.Data;

namespace KeaoDataService
{

    /// <summary>
    /// 适配五骨料仓的拌合站
    /// </summary>
   public class 水稳1:BaseUpLoadInfo
    {
       private string m_File;
       private Thread m_Thread;

       public override bool Init()
       {
           try
           {
               if (!KeaoUtils._DB.InitDataBase(KeaoUtils.Decrypt(KeaoUtils.ConfigGetNodeAttr("系统配置", "数据库"))))
               {
                   KeaoUtils.LogTxt(string.Format("数据库连接失败。"));
                   KeaoUtils.ShowInfoMessage("数据库连接失败。");
                   return false;
               }

               m_File = string.Format("{0}\\ {1}", KeaoUtils.ConfigGetNodeAttr("系统配置", "数据文件"), DateTime.Today.Year);
               if (!File.Exists(m_File))
               {
                   KeaoUtils.LogTxt("没有找到数据文件。");
                   KeaoUtils.ShowInfoMessage("没有找到数据文件。");
                   return false;
               }
               if (!base.Init())
               {
                   KeaoUtils.LogTxt("初始化上传设备失败。");
                   KeaoUtils.ShowInfoMessage("初始化上传设备失败。");
               }
               m_CurrentUploadType = UploadType.水稳料;
               m_LastNum = int.Parse(KeaoUtils.ConfigGetNodeAttr("系统配置", "最新上传行号"));
               m_Thread = new Thread(new ThreadStart(SearchTxt));
               m_Thread.Start();
               return true;

           }
           catch (Exception err)
           {
               KeaoUtils.LogTxt(string.Format("初始化异常。{0}", err.Message));
               return false;
           }
       }

       public override void Close()
       {
           base.Close();
           if (m_UpLoadThread != null)
           {
               m_UpLoadThread.Abort();
           }
       }

       private void SearchTxt()
       {
           while (true)
           {
               try
               {
                   string[] infoList = File.ReadAllLines(m_File);
                   if (infoList.Length > m_LastNum)
                   {
                       for (int i = m_LastNum; i < infoList.Length; i++)
                       {
                           try
                           {
                               if (string.IsNullOrEmpty(infoList[i]))
                               {
                                   m_LastNum++;
                                   KeaoUtils.ConfigSetNodeAttr("系统配置", "最新上传行号", m_LastNum.ToString());
                                   continue;
                               }
                               if (!infoList[i].StartsWith("\"")||!infoList[i].EndsWith("\""))
                               {
                                   m_LastNum++;
                                   KeaoUtils.ConfigSetNodeAttr("系统配置", "最新上传行号", m_LastNum.ToString());
                                   continue;
                               }
                               infoList[i] = infoList[i].Remove(0, 1);
                               infoList[i] = infoList[i].Remove(infoList[i].Length - 1, 1);
                               string[] tmpStrs = infoList[i].Split('*');
                               decimal gl1 = 0m;
                               decimal gl2 = 0m;
                               decimal gl3 = 0m;
                               decimal gl4 = 0m;
                               if (KeaoUtils.ConfigGetNodeAttr("料仓1", "状态") == "启用")
                               {
                                   switch (KeaoUtils.ConfigGetNodeAttr("料仓1", "类型"))
                                   {
                                       case "0-5":
                                           gl1 +=decimal.Parse( tmpStrs[0]);
                                           break;
                                       case "5-10":
                                           gl2 += decimal.Parse( tmpStrs[0]);
                                           break;
                                       case "10-20":
                                           gl3 += decimal.Parse(tmpStrs[0]);
                                           break;
                                       case "20-30":
                                           gl4 += decimal.Parse(tmpStrs[0]);
                                           break;
                                   }
                               }
                               if (KeaoUtils.ConfigGetNodeAttr("料仓2", "状态") == "启用")
                               {
                                   switch (KeaoUtils.ConfigGetNodeAttr("料仓2", "类型"))
                                   {
                                       case "0-5":
                                           gl1 += decimal.Parse(tmpStrs[1]);
                                           break;
                                       case "5-10":
                                           gl2 += decimal.Parse(tmpStrs[1]);
                                           break;
                                       case "10-20":
                                           gl3 += decimal.Parse(tmpStrs[1]);
                                           break;
                                       case "20-30":
                                           gl4 += decimal.Parse(tmpStrs[1]);
                                           break;
                                   }
                               }
                               if (KeaoUtils.ConfigGetNodeAttr("料仓3", "状态") == "启用")
                               {
                                   switch (KeaoUtils.ConfigGetNodeAttr("料仓3", "类型"))
                                   {
                                       case "0-5":
                                           gl1 += decimal.Parse(tmpStrs[2]);
                                           break;
                                       case "5-10":
                                           gl2 += decimal.Parse(tmpStrs[2]);
                                           break;
                                       case "10-20":
                                           gl3 += decimal.Parse(tmpStrs[2]);
                                           break;
                                       case "20-30":
                                           gl4 += decimal.Parse(tmpStrs[2]);
                                           break;
                                   }
                               }
                               if (KeaoUtils.ConfigGetNodeAttr("料仓4", "状态") == "启用")
                               {
                                   switch (KeaoUtils.ConfigGetNodeAttr("料仓4", "类型"))
                                   {
                                       case "0-5":
                                           gl1 += decimal.Parse(tmpStrs[3]);
                                           break;
                                       case "5-10":
                                           gl2 += decimal.Parse(tmpStrs[3]);
                                           break;
                                       case "10-20":
                                           gl3 += decimal.Parse(tmpStrs[3]);
                                           break;
                                       case "20-30":
                                           gl4 += decimal.Parse(tmpStrs[3]);
                                           break;
                                   }
                               }
                               if (KeaoUtils.ConfigGetNodeAttr("料仓5", "状态") == "启用")
                               {
                                   switch (KeaoUtils.ConfigGetNodeAttr("料仓5", "类型"))
                                   {
                                       case "0-5":
                                           gl1 += decimal.Parse(tmpStrs[4]);
                                           break;
                                       case "5-10":
                                           gl2 += decimal.Parse(tmpStrs[4]);
                                           break;
                                       case "10-20":
                                           gl3 += decimal.Parse(tmpStrs[4]);
                                           break;
                                       case "20-30":
                                           gl4 += decimal.Parse(tmpStrs[4]);
                                           break;
                                   }
                               }

                               TableRow newRow = new TableRow() { ID = Guid.NewGuid().ToString(), TableName = "tbl_banhezhan", Ctl = DBCtl.插入 };
                               newRow.DataCols.Add(new TableCol() { ColName = "gl1", ValueMember = gl1, ValueType = DataValueCommonType.数字 });
                               newRow.DataCols.Add(new TableCol() { ColName = "gl2", ValueMember = gl2, ValueType = DataValueCommonType.数字 });
                               newRow.DataCols.Add(new TableCol() { ColName = "gl3", ValueMember = gl3, ValueType = DataValueCommonType.数字 });
                               newRow.DataCols.Add(new TableCol() { ColName = "gl4", ValueMember = gl4, ValueType = DataValueCommonType.数字 });
                               newRow.DataCols.Add(new TableCol() { ColName = "gl5", ValueMember = "0", ValueType = DataValueCommonType.数字 });
                               newRow.DataCols.Add(new TableCol() { ColName = "fl", ValueMember = tmpStrs[5], ValueType = DataValueCommonType.数字 });
                               newRow.DataCols.Add(new TableCol() { ColName = "shui", ValueMember = tmpStrs[6], ValueType = DataValueCommonType.数字 });
                               newRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "0", ValueType = DataValueCommonType.字符串 });
                               newRow.DataCols.Add(new TableCol() { ColName = "kehubianhao", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "客户编号"), ValueType = DataValueCommonType.字符串 });
                               newRow.DataCols.Add(new TableCol() { ColName = "zhandian", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "站点"), ValueType = DataValueCommonType.字符串 });
                               newRow.DataCols.Add(new TableCol() { ColName = "shijian", ValueMember = tmpStrs[7], ValueType = DataValueCommonType.日期时间 });
                               KeaoUtils._DB.SaveTableRows(newRow);
                           }
                           catch (Exception err)
                           {
                               KeaoUtils.LogTxt(string.Format("解析拌合站数据异常。{0}#{1}", infoList[i], err.Message));
                           }
                           m_LastNum++;
                           KeaoUtils.ConfigSetNodeAttr("系统配置", "最新上传行号", m_LastNum.ToString());
                       }
                   }
                   if (KeaoUtils.ConfigGetNodeAttr("网络设备", "类型") == "KeaoDTU"&&KeaoUtils.ConfigGetNodeAttr("时段","日结提醒")=="启用"&&base.UpLoadStatus)
                   {
                       #region 短信提醒
                       DateTime nowDate = DateTime.Now;
                       if (nowDate.Hour >= int.Parse(KeaoUtils.ConfigGetNodeAttr("时段", "提醒时间")) && KeaoUtils.ConfigGetNodeAttr("网络设备", "短信发送日期") != nowDate.ToString("yyyy-MM-dd"))
                       {
                           KeaoUtils.ConfigSetNodeAttr("网络设备", "短信发送日期", nowDate.ToString("yyyy-MM-dd"));
                           StringBuilder sendStr = new StringBuilder();
                           DateTime kaiShi = DateTime.Today.AddDays(-1);
                           DateTime jieShu = kaiShi.AddHours(23).AddMinutes(59).AddSeconds(59);
                           string createCondition = KeaoUtils._DB.CreateAndCondition("shijian", DataValueCommonType.日期时间, kaiShi.ToString("yyyy-MM-dd HH:mm:ss"), jieShu.ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
                           createCondition += KeaoUtils._DB.CreateAndCondition("zhandian", DataValueCommonType.字符串, KeaoUtils.ConfigGetNodeAttr("客户", "站点"), "", SearchConditionType.等于);
                           DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_banhezhan", "sum(gl1) as gl1,sum(gl2) as gl2,sum(gl3) as gl3,sum(gl4) as gl4,sum(gl5) as gl5,sum(fl) as fl,sum(shui) as shui,sum(gl1+gl2+gl3+gl4+gl5+fl+shui) as hanshui,sum(gl1+gl2+gl3+gl4+gl5+fl) as buhanshui", null, createCondition, "zhandian", null);
                           if (Dt.Rows.Count > 0)
                           {
                               sendStr.Append(string.Format("[站点：{0}]\n", KeaoUtils.ConfigGetNodeAttr("客户", "站点")));
                               if (KeaoUtils.ConfigGetNodeAttr("料仓1", "状态") == "启用")
                               {
                                  sendStr.Append(string.Format("{0}:{1}吨\n", KeaoUtils.ConfigGetNodeAttr("料仓1", "类型"), Dt.Rows[0]["gl1"]));
                               }
                               if (KeaoUtils.ConfigGetNodeAttr("料仓2", "状态") == "启用")
                               {
                                   sendStr.Append(string.Format("{0}:{1}吨\n", KeaoUtils.ConfigGetNodeAttr("料仓2", "类型"), Dt.Rows[0]["gl2"]));
                               }
                               if (KeaoUtils.ConfigGetNodeAttr("料仓3", "状态") == "启用")
                               {
                                   sendStr.Append( string.Format("{0}:{1}吨\n", KeaoUtils.ConfigGetNodeAttr("料仓3", "类型"), Dt.Rows[0]["gl3"]));
                               }
                               if (KeaoUtils.ConfigGetNodeAttr("料仓4", "状态") == "启用")
                               {
                                   sendStr.Append( string.Format("{0}:{1}吨\n", KeaoUtils.ConfigGetNodeAttr("料仓4", "类型"), Dt.Rows[0]["gl4"]));
                               }
                               if (KeaoUtils.ConfigGetNodeAttr("料仓5", "状态") == "启用")
                               {
                                  sendStr.Append( string.Format("{0}:{1}吨\n", KeaoUtils.ConfigGetNodeAttr("料仓5", "类型"), Dt.Rows[0]["gl5"]));
                               }
                               sendStr.Append( string.Format("水泥:{0}吨\n", Dt.Rows[0]["fl"]));
                               sendStr.Append( string.Format("水:{0}吨\n", Dt.Rows[0]["shui"]));
                               sendStr.Append( string.Format("含水合计:{0}吨\n", Dt.Rows[0]["hanshui"]));
                               sendStr.Append( string.Format("不含水合计:{0}吨\n", Dt.Rows[0]["buhanshui"]));
                           }

                           if (sendStr.Length > 0)
                           {
                               if (sendStr.Length <= 145)
                               {
                                   XmlNodeList nodeList = KeaoUtils.ConfigGetNodeListByTag("发送号码");
                                   foreach (XmlNode node in nodeList)
                                   {
                                       base.SendSMS(sendStr.ToString(), node.InnerText);
                                   }
                               }
                               else
                               {
                                   XmlNodeList nodeList = KeaoUtils.ConfigGetNodeListByTag("发送号码");
                                   for (int i = 0; i < sendStr.Length; i += 145)
                                   {
                                       if (i + 145 > sendStr.Length)
                                       {
                                           foreach (XmlNode node in nodeList)
                                           {
                                               base.SendSMS(sendStr.ToString().Substring(i), node.InnerText);
                                           }
                                           break;
                                       }

                                       foreach (XmlNode node in nodeList)
                                       {
                                           base.SendSMS(sendStr.ToString().Substring(i, 145), node.InnerText);
                                       }
                                   }
                               }
                           }
                       }
                       #endregion
                   }
               }
               catch (ThreadAbortException)
               {
                   return;
               }
               catch (Exception err)
               {
                   KeaoUtils.LogTxt(string.Format("查找数据文件异常。{0}", err.Message));
               }

               Thread.Sleep(m_Refresh);
           }
       }
    }
}
